package com.fintech.pangu.upms.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fintech.pangu.upms.config.MultiTenantUtil;
import com.fintech.pangu.upms.web.dao.SysPermissionDao;
import com.fintech.pangu.upms.web.dto.SysPermissionDto;
import com.fintech.pangu.upms.web.entity.SysPermission;
import com.fintech.pangu.upms.web.mapper.PermissionMapper;
import com.fintech.pangu.upms.web.service.SysPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Admin
 * @since 2019-10-08
 */
@Service
public class SysPermissionServiceImpl implements SysPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private SysPermissionDao sysPermissionDao;

    @Override
    public List<SysPermissionDto> permissionTreeData() {
        String tenantId = MultiTenantUtil.get();
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StringUtils.isNotEmpty(tenantId),SysPermission::getTenantId,tenantId);
        List<SysPermission> permissionList = sysPermissionDao.selectList(queryWrapper);
        return permissionMapper.po2DtoList(permissionList);
    }

    @Override
    public List<SysPermissionDto> listForRolePermission(Long roleId) {
        List<SysPermission> rolePermissionList =  sysPermissionDao.listForRolePermission(roleId);
        return permissionMapper.po2DtoList(rolePermissionList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long addPermission(SysPermissionDto sysPermissionDto) {
        SysPermission sysPermission = permissionMapper.dto2Po(sysPermissionDto);
        sysPermission.setTenantId( MultiTenantUtil.get());
        sysPermissionDao.insert(sysPermission);
        return sysPermission.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePermission(SysPermissionDto sysPermissionDto) {
        SysPermission sysPermission = permissionMapper.dto2Po(sysPermissionDto);
        sysPermission.setTenantId(MultiTenantUtil.get());
        sysPermissionDao.updateById(sysPermission);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deletePermission(Long id) {
        sysPermissionDao.deleteById(id);
    }
}
